package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:30
 * https://leetcode-cn.com/problems/edit-distance/
 */
public class Title72 {

    /**
     * dp[i][j]表示：[0 - i-1]的A转换为[0 - j-1]的B所使用的的最少操作数。
     * 递推公式：    if(word1.charAt(i-1) == word2.charAt(j-1)) dp[i][j] = dp[i-1][j-1];
     *               不相等：
     *
     *                      增   dp[i][j] = dp[i][j-1] + 1  a  ad
     *                      删   dp[i][j] = dp[i-1][j] + 1  aab aa
     *                     替换  dp[i][j] = dp[i-1][j-1] + 1
     * 初始化：
     * @param word1
     * @param word2
     * @return
     */
    public static int minDistance(String word1, String word2) {
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 0; i <= word1.length(); i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= word2.length(); j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= word1.length(); i++) {
            for (int j = 1; j <= word2.length(); j++) {
                if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 1, Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1));
                }else{
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }


    public int minDistance22(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        //dp[i][j]表示下标为i-1,j-1的字符串s转换为t所需要的最少步数，可以增删改
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 0; i <= n; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= m; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                }else{
                    //替换 删除
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
                }
            }
        }
        return dp[n][m];
    }

    public static void main(String[] args) {
        minDistance("horse", "ros");
        StringBuilder stringBuilder = new StringBuilder();

    }
}
